from time import sleep
class BasePage(object):
    def __init__(self, driver):
        self.driver = driver

    def get_xpath_element(self, locator):
        """获取xpath定位元素进行操作"""
        return self.driver.xpath(locator)
    
    def get_first_classname_element_text(self, locator, index):
        """获取第一个className元素的文本内容"""
        element = self.driver(className=locator)[index].get_text()
        return element

    def click_xpath(self, locator):
        """点击xpath定位的元素"""
        self.driver.xpath(locator).click()


    def click_position(self, x, y):
        """点击指定坐标"""
        width, height = self.driver.info['displayWidth'], self.driver.info['displayHeight']
        self.driver.click(width*x, height*y)

    def set_xpath_text(self, locator, text):
        """指定xpath定位元素写入文本"""
        while self.is_xpath_exist(locator):
            self.driver.xpath(locator).set_text(text)
            break
        else:
            sleep(1)

    def get_xpath_text(self, locator):
        """获取xpath定位元素的文本"""
        return self.driver.xpath(locator).get_text()


    def get_resourceid_text(self, resourceid):
        """根据resourceid获取元素文本内容"""
        return self.driver.resourceId(resourceid).get_text(10)

    def drag_and_drop(self, start, end):
        """起止坐标元素滑动"""
        self.driver.xpath(start).drag_to(self.driver.xpath(end).bounds.center())

    def swipe(self, direction, distance):
        """向指定方向滑动指定比例"""
        self.driver.swipe_ext(direction, distance)
        
    def swipe_position(self, start_position, end_position, duration=0.3):
        """根据指定坐标位置滑动"""
        width, height = self.driver.info['displayWidth'], self.driver.info['displayHeight']
        self.driver.swipe(int(start_position[0]*width), int(start_position[1]*height), int(end_position[0]*width), int(end_position[1]*height), duration)

    def is_text_toast_exist(self, text):
        """判断指定toast提示是否存在"""
        toast_msg = self.driver.toast.get_message(10, default='')
        if text in toast_msg:
            return True
        else:
            return False

    def is_xpath_exist(self, locator):
        """判断指定xpath元素是否存在"""
        result = self.driver.xpath(locator).exists
        return result

    def is_resource_id_exist(self, resource_id, timeout=5):
        """根据resource ID 判断元素是否存在"""
        try:
            self.driver(resourceId=resource_id).exists(timeout)
            print("存在指定元素")
            return True
        except Exception as e:
            print(e, "不存在指定元素")
            return False

    def long_press(self, locator):
        """长按指定xpath元素"""
        while self.is_xpath_exist(locator):
            self.driver.xpath(locator).long_click()
            break
        else:
            sleep(1)
        
    def double_click(self, locator):
        """双击指定元素"""
        while self.is_xpath_exist(locator):
            self.driver.xpath(locator).double_click()
            break
        else:
            sleep(1)